<?php

class Application_Model_Mapper_KommentarMapper
{
	protected $_dbTable;

	public function setDbTable ($dbTable)
	{
		
		if (is_string($dbTable))
		{
			$dbTable = new $dbTable();
		}
		if (! $dbTable instanceof Zend_Db_Table_Abstract)
		{
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
		
	}

	public function getDbTable ()
	{
		
		if (null === $this->_dbTable)
		{
			$this->setDbTable('Application_Model_DbTable_Kommentar');
		}
		return $this->_dbTable;
		
	}

	public function add (Application_Model_Kommentar $kommentar)
	{		
		

		$now = new DateTime();
		$generatedid = Helper_Idgenerator::getid();
		$generatedidcheck = $this->fetchID($generatedid);
		if(empty($generatedidcheck)){
		
			$data = array(
					'id' => $generatedid,
					'created' => date('Y-m-d H:i:s'),
					'referenzid' => $kommentar->getReferenzid(),
					'referenzobjekt' => $kommentar->getReferenzobjekt(),
					'text' => $kommentar->getText(),
					'userID' => $kommentar->getUserID(),
					'deleted' => '0',
			);
	
			return $this->getDbTable()->insert($data);
		}
		else{
			$this->add($$kommentar);
		}
		
	}

	public function delete ($id)
	{
		$data = array(
				'deleted' => true);
		return $this->getDbTable()->update($data, array(
				'id = ?' => $id));
	}


	public function fetchID($id)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		$entry->from('kommentar');
		$entry->where('kommentar.id = ?', $id);
		$entry->where('kommentar.deleted = 0');
		return $entry->query()->fetch();
	}


	public function fetchIdAndObjekt($referenzid, $referenzobjekt)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		// 		$entry = $this->getDbTable();
		$entry->from('kommentar');
		$entry->where('kommentar.referenzid = ?', $referenzid);
		$entry->where('kommentar.referenzobjekt = ?', $referenzobjekt);
		$entry->where('kommentar.deleted = 0');
		$entry->order('created DESC');
		$entry->joinleft(array('user' => 'users', array('id' => 'id')),
				'kommentar.userID = user.id',
				'vorname as vorname');
		return $entry->query()->fetchall();
	}

}




